package web.zz.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import web.zz.bean.Log_info;
import web.zz.bean.User;

import java.sql.*;

@Repository
public class LogDao {
    @Autowired
    private static JdbcTemplate jdbcTemplate;
    final boolean RES_SUCCESS = true;
    final boolean RES_FAILURE = false;

    public static void insert(Log_info loginInfo) throws SQLException, ClassNotFoundException {
        boolean result;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;

        String sql = "INSERT INTO user_log(username) values (${username})";
        connection = getCon();
        statement = connection.createStatement();
        resultSet = statement.executeQuery(sql);
        preparedStatement.setString(1, loginInfo.getUsername());

        close(connection,statement,resultSet);
    }

    public static Connection getCon() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT","root","123456");

    }
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static Log_info insert(String username) throws SQLException, ClassNotFoundException {
        boolean result;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;

        String sql = "INSERT INTO user_log(username) values (${username})";
        connection = getCon();
        statement = connection.createStatement();
        resultSet = statement.executeQuery(sql);
        RowMapper<Log_info> rowMapper = new BeanPropertyRowMapper<Log_info>(Log_info.class);
        try {
            return jdbcTemplate.queryForObject(sql,new Object[]{username},rowMapper);
        }catch (EmptyResultDataAccessException e){
            return null;
        }

    }
}
